package fun.stgoder.test1;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestProducerConsumerQueue {

    public static void main(String[] args) {
        SQueue<Integer> sQueue = new SQueue<>(10);

        // consumer
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                while (true) {
                    Integer integer = sQueue.get();
                    System.out.println(integer);


                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        // producer
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                while (true) {
                    sQueue.put(1);

                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}

class SQueue<E> {
    private int limit;
    private Queue<E> queue;

    private Lock lock;
    private Condition putCondition;
    private Condition getCondition;

    public SQueue(int limit) {
        this.limit = limit;
        this.queue = new LinkedList<>();

        this.lock = new ReentrantLock();
        this.putCondition = lock.newCondition();
        this.getCondition = lock.newCondition();
    }

    public void put(E e) {
        lock.lock();
        try {
            while (queue.size() >= limit) {
                System.out.println("put await");
                putCondition.await();
                System.out.println("put awake");
            }
            boolean offer = queue.offer(e);
            if (offer) {
                getCondition.signal();
            }
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public E get() {
        E e = null;
        lock.lock();
        try {
            while (queue.size() == 0) {
                System.out.println("get await");
                getCondition.await();
                System.out.println("get awake");
            }
            e = queue.poll();
            putCondition.signal();
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        } finally {
            lock.unlock();
        }
        return e;
    }

    public int size() {
        lock.lock();
        try {
            return queue.size();
        } finally {
            lock.unlock();
        }
    }
}
